<template>
  <el-dialog
    :model-value="visible"
    title="社区分配管理"
    width="1200px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @update:model-value="handleVisibleChange"
    @close="handleClose"
  >
    <div class="community-assign-container">
      <!-- 物业公司信息 -->
      <div class="property-company-section">
        <h3>物业公司信息</h3>
        <div class="company-info">
          <div class="company-name">{{ propertyCompany?.companyName }}</div>
          <div class="company-code">编码：{{ propertyCompany?.companyCode }}</div>
        </div>
      </div>

      <!-- 社区分配区域 -->
      <div class="community-assign-section">
        <h3>社区分配</h3>
        <div class="assign-content">
          <!-- 左侧：可分配的社区 -->
          <div class="available-communities">
            <h4>可分配社区</h4>
            <el-input
              v-model="availableSearchKeyword"
              placeholder="搜索社区名称或区域"
              prefix-icon="Search"
              clearable
              @input="handleAvailableSearch"
            />
            <div class="community-list">
              <el-checkbox-group v-model="selectedCommunities">
                <div
                  v-for="community in filteredAvailableCommunities"
                  :key="community.id"
                  class="community-item"
                >
                  <el-checkbox :value="community.id">
                    <div class="community-info">
                      <div class="community-name">{{ community.communityName }}</div>
                      <div class="community-code">编码：{{ community.communityCode }}</div>
                      <div class="community-region">{{ community.regionFullName }}</div>
                      <div class="community-address">{{ community.address }}</div>
                    </div>
                  </el-checkbox>
                </div>
              </el-checkbox-group>
              <div v-if="filteredAvailableCommunities.length === 0" class="empty-tip">
                暂无可分配的社区
              </div>
            </div>
          </div>

          <!-- 中间：操作按钮 -->
          <div class="assign-actions">
            <el-button
              type="primary"
              :disabled="!selectedCommunities.length"
              @click="assignCommunities"
            >
              <el-icon><ArrowRight /></el-icon>
              分配
            </el-button>
            <el-button
              type="danger"
              :disabled="!selectedAssignedCommunities.length"
              @click="unassignCommunities"
            >
              <el-icon><ArrowLeft /></el-icon>
              取消分配
            </el-button>
          </div>

          <!-- 右侧：已分配的社区 -->
          <div class="assigned-communities">
            <h4>已分配社区</h4>
            <el-input
              v-model="assignedSearchKeyword"
              placeholder="搜索社区名称或区域"
              prefix-icon="Search"
              clearable
              @input="handleAssignedSearch"
            />
            <div class="community-list">
              <el-checkbox-group v-model="selectedAssignedCommunities">
                <div
                  v-for="community in filteredAssignedCommunities"
                  :key="community.id"
                  class="community-item"
                >
                  <el-checkbox :value="community.id">
                    <div class="community-info">
                      <div class="community-name">{{ community.communityName }}</div>
                      <div class="community-code">编码：{{ community.communityCode }}</div>
                      <div class="community-region">{{ community.regionFullName }}</div>
                      <div class="community-address">{{ community.address }}</div>
                    </div>
                  </el-checkbox>
                </div>
              </el-checkbox-group>
              <div v-if="filteredAssignedCommunities.length === 0" class="empty-tip">
                暂无已分配的社区
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSave" :loading="saving">
          保存分配
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { ArrowRight, ArrowLeft } from '@element-plus/icons-vue'
import { showSuccess, showError, showWarning } from '@/utils/message'
import { useUserStore } from '@/store/user'
import { hasMenuPermission } from '@/utils/permission'
import { propertyCompanyApi } from '@/api/property/propertyCompany'

// 作者：Wu.Liang
// 创建时间：2025-01-30
// 功能：物业公司社区分配管理弹窗组件

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  propertyCompany: {
    type: Object,
    default: null
  }
})

const emit = defineEmits(['update:visible', 'success', 'cancel'])

const userStore = useUserStore()

// 权限检查
const isSuperAdmin = computed(() => userStore.isAdmin())

const hasAssignPermission = computed(() => {
  return hasMenuPermission('property:company:menu')
})

// 响应式数据
const availableCommunities = ref([])
const assignedCommunities = ref([])
const selectedCommunities = ref([])
const selectedAssignedCommunities = ref([])
const availableSearchKeyword = ref('')
const assignedSearchKeyword = ref('')
const saving = ref(false)

// 计算属性
const filteredAvailableCommunities = computed(() => {
  if (!availableSearchKeyword.value) {
    return availableCommunities.value
  }
  
  return availableCommunities.value.filter(community => {
    const communityName = community.communityName || ''
    const regionFullName = community.regionFullName || ''
    const searchKeyword = availableSearchKeyword.value.toLowerCase()
    
    return communityName.toLowerCase().includes(searchKeyword) || 
           regionFullName.toLowerCase().includes(searchKeyword)
  })
})

const filteredAssignedCommunities = computed(() => {
  if (!assignedSearchKeyword.value) {
    return assignedCommunities.value
  }
  
  return assignedCommunities.value.filter(community => {
    const communityName = community.communityName || ''
    const regionFullName = community.regionFullName || ''
    const searchKeyword = assignedSearchKeyword.value.toLowerCase()
    
    return communityName.toLowerCase().includes(searchKeyword) || 
           regionFullName.toLowerCase().includes(searchKeyword)
  })
})

// 监听器
watch(() => props.visible, (newVal) => {
  if (newVal) {
    // 检查权限
    if (!hasAssignPermission.value) {
      showError('您没有社区分配权限')
      emit('update:visible', false)
      return
    }
    
    // 检查物业公司信息
    if (!props.propertyCompany) {
      showError('物业公司信息不能为空')
      emit('update:visible', false)
      return
    }
    
    initData()
  }
})

// 方法
const initData = async () => {
  try {
    await Promise.all([
      loadAvailableCommunities(),
      loadAssignedCommunities()
    ])
    resetSelection()
  } catch (error) {
    console.error('初始化数据失败:', error)
    showError('初始化数据失败')
  }
}

const loadAvailableCommunities = async () => {
  try {
    const response = await propertyCompanyApi.getAvailableCommunities(
      props.propertyCompany.id, 
      availableSearchKeyword.value
    )
    if (response.code === 200) {
      availableCommunities.value = response.data || []
    } else {
      showError(response.message || '获取可分配社区列表失败')
    }
  } catch (error) {
    console.error('获取可分配社区列表失败:', error)
    showError('获取可分配社区列表失败')
  }
}

const loadAssignedCommunities = async () => {
  try {
    const response = await propertyCompanyApi.getAssignedCommunities(
      props.propertyCompany.id,
      assignedSearchKeyword.value
    )
    if (response.code === 200) {
      assignedCommunities.value = response.data || []
    } else {
      showError(response.message || '获取已分配社区失败')
    }
  } catch (error) {
    console.error('获取已分配社区失败:', error)
    showError('获取已分配社区失败')
  }
}

const handleAvailableSearch = () => {
  loadAvailableCommunities()
}

const handleAssignedSearch = () => {
  loadAssignedCommunities()
}

const assignCommunities = async () => {
  if (selectedCommunities.value.length === 0) {
    showWarning('请选择要分配的社区')
    return
  }
  
  try {
    const response = await propertyCompanyApi.assignCommunities({
      propertyCompanyId: props.propertyCompany.id,
      communityIds: selectedCommunities.value
    })
    
    if (response.code === 200) {
      showSuccess('社区分配成功')
      await Promise.all([
        loadAvailableCommunities(),
        loadAssignedCommunities()
      ])
      resetSelection()
    } else {
      showError(response.message || '社区分配失败')
    }
  } catch (error) {
    console.error('社区分配失败:', error)
    showError('社区分配失败')
  }
}

const unassignCommunities = async () => {
  if (selectedAssignedCommunities.value.length === 0) {
    showWarning('请选择要取消分配的社区')
    return
  }
  
  try {
    const response = await propertyCompanyApi.unassignCommunities({
      propertyCompanyId: props.propertyCompany.id,
      communityIds: selectedAssignedCommunities.value
    })
    
    if (response.code === 200) {
      showSuccess('取消分配成功')
      await Promise.all([
        loadAvailableCommunities(),
        loadAssignedCommunities()
      ])
      resetSelection()
    } else {
      showError(response.message || '取消分配失败')
    }
  } catch (error) {
    console.error('取消分配失败:', error)
    showError('取消分配失败')
  }
}

const resetSelection = () => {
  selectedCommunities.value = []
  selectedAssignedCommunities.value = []
  availableSearchKeyword.value = ''
  assignedSearchKeyword.value = ''
}

const handleVisibleChange = (value) => {
  emit('update:visible', value)
}

const handleClose = () => {
  emit('cancel')
}

const handleSave = () => {
  // 保存操作已经在分配和取消分配时完成
  emit('success')
}
</script>

<style scoped>
.community-assign-container {
  padding: 20px 0;
}

.property-company-section {
  margin-bottom: 24px;
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 8px;
}

.property-company-section h3 {
  margin: 0 0 12px 0;
  font-size: 16px;
  color: #303133;
}

.company-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.company-name {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.company-code {
  font-size: 14px;
  color: #606266;
}

.community-assign-section h3 {
  margin: 0 0 16px 0;
  font-size: 16px;
  color: #303133;
}

.assign-content {
  display: flex;
  gap: 20px;
  height: 500px;
}

.available-communities,
.assigned-communities {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.available-communities h4,
.assigned-communities h4 {
  margin: 0 0 12px 0;
  font-size: 14px;
  color: #606266;
}

.community-list {
  flex: 1;
  overflow-y: auto;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 8px;
}

.community-item {
  margin-bottom: 12px;
  padding: 8px;
  border-radius: 4px;
  background-color: #fafafa;
  transition: background-color 0.2s;
}

.community-item:hover {
  background-color: #f0f0f0;
}

.community-item:last-child {
  margin-bottom: 0;
}

.community-info {
  margin-left: 8px;
}

.community-name {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.community-code {
  font-size: 12px;
  color: #909399;
  margin-bottom: 2px;
}

.community-region {
  font-size: 12px;
  color: #409eff;
  margin-bottom: 2px;
}

.community-address {
  font-size: 12px;
  color: #606266;
}

.empty-tip {
  text-align: center;
  color: #909399;
  font-size: 14px;
  padding: 40px 0;
}

.assign-actions {
  display: flex;
  flex-direction: column;
  justify-content: center;
  gap: 12px;
  padding: 0 16px;
}

.dialog-footer {
  text-align: right;
}
</style> 